import React, { Component, Children, isValidElement } from "react"
import Space from "components/space"
import ReactDOM from 'react-dom'

class Template extends Component {

  defaultHeight = 66;

  state = {
    headHeight: this.defaultHeight
  };

  componentDidMount () {
    const domNode = this.refs.getHeight;
    this.setState({
      headHeight: domNode ?
        ReactDOM.findDOMNode(domNode).getBoundingClientRect().height + this.defaultHeight + 12
        : this.defaultHeight
    });
  }

  haveTabs = () => {
    this.defaultHeight = 50;
  };

  render () {
    const { children, ...otherProps } = this.props;
    const { headHeight } = this.state;
    return (
      <Space size={'middle'} direction={'vertical'} {...otherProps}>
        {Children.map(children, child => React.cloneElement(child,
          child.type.defaultProps &&
          child.type.defaultProps.identity === 'Header' ? {
            ref: 'getHeight',
            haveTabs: this.haveTabs
          } : { headHeight }))}
      </Space>
    )
  }

}

class Header extends Component {

  render () {
    const { children, haveTabs } = this.props;
    let isTabs = children.type && children.type.defaultProps && children.type.defaultProps.prefixCls === 'ant-tabs';
    let isCardMode = isTabs && children.props.type === 'card';
    return (
      <div>
        {
          isTabs && !isCardMode ? (
            <div style={{ marginTop: '-16px' }}>
              {Children.map(children, child => {
                haveTabs();
                return React.cloneElement(child, { className: `template-tabs ${child.props.className || ''}` });
              })}
            </div>
          ) : (
            <Space size={'middle'} direction={'vertical'}>
              {Children.map(children, child => isValidElement(child) ? child : <div style={{ display: 'none' }}/>)}
            </Space>
          )
        }
      </div>
    )
  }

  static defaultProps = {
    identity: 'Header'
  }

}

class Middle extends Component {

  render () {
    const { headHeight, children } = this.props;
    return (
      <div className={'full-height-page'} style={{ height: `calc(100vh - ${headHeight}px)` }}>
        {children}
      </div>
    )
  }

}

Template.Header = Header;

Template.Middle = Middle;

export default Template;
